import {Component, OnInit} from '@angular/core';
import {Location} from '@angular/common';
import {Router} from '@angular/router';
import {FormBuilder, FormControl, FormGroup, ValidationErrors, Validators} from '@angular/forms';
import {Observable, Observer} from 'rxjs';
import {HttpClient} from '@angular/common/http';

@Component({
  selector: 'app-new',
  templateUrl: './new.component.html',
  styleUrls: ['./new.component.scss']
})
export class NewComponent implements OnInit {
  validateForm: FormGroup;
  timestamp = 0;

  constructor(
    private location: Location,
    private router: Router,
    private fb: FormBuilder,
    private http: HttpClient,
  ) {
    this.validateForm = this.fb.group({
      id: [],
      host: ['', [Validators.required,], [this.hostAsyncValidator]],
      port: [22, [Validators.required]],
      username: ['', [Validators.required]],
      password: ['', [Validators.required]],
      name: ['', [Validators.required]],
    });
  }

  ngOnInit() {
  }

  backward() {
    this.location.back();
  }

  submitForm(value: any): void {
    for (const key in this.validateForm.controls) {
      if (key) {
        this.validateForm.controls[key].markAsDirty();
        this.validateForm.controls[key].updateValueAndValidity();
      }
    }
    this.http.post('/api/initialization/saveServer', value).subscribe(() => {
      this.router.navigate(['/server']);
    });
  }

  hostAsyncValidator = (control: FormControl) =>
    new Observable((observer: Observer<ValidationErrors | null>) => {
      setTimeout(() => {
        if (!observer.closed) {
          const currentTime = new Date().getTime();
          if (this.timestamp === 0 || currentTime - this.timestamp > 500) {
            this.timestamp = currentTime;
            this.http.get('/api/initialization/isServerHostExist/' + control.value).subscribe(res => {
              if (res) {
                observer.next({error: true, duplicated: true});
              } else {
                observer.next(null);
              }
              observer.complete();
            });
          }
        }
      }, 500);
    });

  resetForm(e: MouseEvent): void {
    e.preventDefault();
    this.validateForm.reset();
    for (const key in this.validateForm.controls) {
      if (key) {
        this.validateForm.controls[key].markAsPristine();
        this.validateForm.controls[key].updateValueAndValidity();
      }
    }
  }
}
